<template>
    <base-breadcrumb :breadcrumb="!isAudit" :title="title">
        <template>
            <a-card class="mb20">
                <titleName title="基础信息填写" />
                <a-form-model
                    ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
                >
                    <a-row :gutter="24">
                            <a-col :md="16" :sm="16">
                                <a-form-model-item label="所属单位" prop="projectId" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                                    <org-tree-select v-model="form.projectId"
                                                     disabled
                                                     :is-query-projec-detail="false"
                                                     isAutoSelectFirst
                                                     checkStrictly></org-tree-select>
                                </a-form-model-item>
                            </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="名称：" prop="name">
                                <BaseInput v-model="form.name" :disabled="type == 'look'" placeholder="请输入" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="合同额（元）：" prop="contractValue">
                                <BaseInputNumber
                                    v-model="form.contractValue"
                                    :max="99999999999999"
                                    :disabled="type == 'look'"
                                    :min="0"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="发包人确认工程量（元）：" prop="confirmsProjectQuantity">
                                <BaseInputNumber
                                    v-model="form.confirmsProjectQuantity"
                                    :max="99999999999999"
                                    :disabled="type == 'look'"
                                    :min="0"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="结算基本值（含税）（元）：" prop="basicSettlementValue">
                                <BaseInputNumber
                                    v-model="form.basicSettlementValue"
                                    :max="99999999999999"
                                    :disabled="type == 'look'"
                                    :min="0"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="结算保底值（含税）（元）：" prop="settlementGuarantee">
                                <BaseInputNumber
                                    v-model="form.settlementGuarantee"
                                    :max="99999999999999"
                                    :disabled="type == 'look'"
                                    :min="0"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="结算报送值（含税）（元）：" prop="settlementReportValue">
                                <BaseInputNumber
                                    v-model="form.settlementReportValue"
                                    :max="99999999999999"
                                    :disabled="type == 'look'"
                                    :min="0"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="实际成本（含税）（元）：" prop="actualCost">
                                <BaseInputNumber
                                    v-model="form.actualCost"
                                    :max="99999999999999"
                                    :disabled="type == 'look'"
                                    :min="0"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="已收款（元）：" prop="paidFor">
                                <BaseInputNumber
                                    v-model="form.paidFor"
                                    :max="99999999999999"
                                    :disabled="type == 'look'"
                                    :min="0"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="合同约定结算书报送时间：" prop="reportingTime">
                                <a-date-picker
                                    v-model="form.reportingTime"
                                    :disabled="type == 'look'"
                                    @change="(date, dateString) => getTime(date, dateString, 'form', 'reportingTime')"
                                />
                                <!-- <a-range-picker @change="fill" v-model="form.reportingTime" /> -->
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="策划完成时间：" prop="compleDate">
                                <a-date-picker
                                        v-model="form.compleDate"
                                        :disabled="type == 'look'"
                                        value-format="YYYY-MM-DD"
                                        format="YYYY-MM-DD"
                                />
                                <!-- <a-range-picker @change="fill" v-model="form.reportingTime" /> -->
                            </a-form-model-item>
                        </a-col>

                    </a-row>
                    <a-row :gutter="24" class="prompt-bg">
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="预计利润率(基本值)(%)">
                                <BaseInputNumber
                                    :max="99999999999999"
                                    disabled
                                    placeholder="请输入"
                                    :precision="2"
                                    :value="
                                        ((form.basicSettlementValue - form.actualCost) / form.basicSettlementValue) *
                                        100
                                            ? ((form.basicSettlementValue - form.actualCost) /
                                                  form.basicSettlementValue) *
                                              100
                                            : 0
                                    "
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="预计利润率(保底值(%)" prop="paidFor">
                                <BaseInputNumber
                                    :max="99999999999999"
                                    disabled
                                    placeholder="请输入"
                                    :precision="2"
                                    :value="
                                        ((form.settlementGuarantee - form.actualCost) / form.settlementGuarantee) * 100
                                            ? ((form.settlementGuarantee - form.actualCost) /
                                                  form.settlementGuarantee) *
                                              100
                                            : 0
                                    "
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="预计利润率(报送值)(%)" prop="paidFor">
                                <BaseInputNumber
                                    :max="99999999999999"
                                    disabled
                                    placeholder="请输入"
                                    :precision="2"
                                    :value="
                                        ((form.settlementReportValue - form.actualCost) / form.settlementReportValue) *
                                        100
                                            ? ((form.settlementReportValue - form.actualCost) /
                                                  form.settlementReportValue) *
                                              100
                                            : 0
                                    "
                                />
                            </a-form-model-item>
                        </a-col>
                    </a-row>
<!--                    <a-row>-->
<!--                                    <a-col-->
<!--                                            :md="8"-->
<!--                                            :sm="8"-->
<!--                                    >-->
<!--                                      <a-form-model-item-->
<!--                                              label="填报人"-->
<!--                                              :label-col="{ lg: { span: 2 }, sm: { span: 2 } }"-->
<!--                                              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"-->
<!--                                      >-->
<!--                                      <base-input v-model="form.createName" disabled></base-input>-->
<!--                                      </a-form-model-item>-->
<!--                                    </a-col>-->
<!--                    </a-row>-->
                    <a-row>
                        <a-col v-if="type != 'look'" :md="16" :sm="16">
                            <a-form-model-item
                                label="附件上传"
                                :label-col="{ lg: { span: 3 }, sm: { span: 3 } }"
                                :wrapper-col="{ lg: { span: 18 }, sm: { span: 17 } }"
                            >
                                <l-table
                                    v-if="isUpdate"
                                    :upload-arrys="form.fileInfoVOList"
                                    business-code="BM01"
                                    @fileArrysData="fileArrysData"
                                />
                            </a-form-model-item>
                        </a-col>

                        <a-col v-else :md="24" :sm="24">
                            <a-form-model-item label="附件：" prop="branchComId">
                                <file-link :file-list="form.fileInfoVOList" />
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </a-card>
            <div v-if="type != 'look' && !isConsultation" class="tool-btns mb20 page-btn-right-top">
<!--                <a-button-->
<!--                    v-if="id != '' && form.auditStatus == 'DRAFT'"-->
<!--                    :loading="loading.DELETE"-->
<!--                    type="danger"-->
<!--                    @click="deleteDraft"-->
<!--                >-->
<!--                    删除草稿-->
<!--                </a-button>-->
<!--                <a-button-->
<!--                    v-if="form.auditStatus == 'REJECTED'"-->
<!--                    type="primary"-->
<!--                    :loading="loading.REJECTED"-->
<!--                    @click="submitForm('REJECTED')"-->
<!--                >-->
<!--                    保存-->
<!--                </a-button>-->
                <a-button  :loading="loading.DRAFT" type="primary" @click="submitForm('DRAFT')">
                    保存草稿
                </a-button>
                <a-button :loading="loading.SUBMITTED" type="primary" @click="submitForm('SUBMITTED')"> 提交 </a-button>
                <a-button type="primary" @click="closeForm"> 关闭 </a-button>
            </div>
            <div v-else-if="!isConsultation" class="tool-btns page-btn-right-top">
                <a-button v-if="checkVisibleInDetail" type="primary" @click="closeForm"> 关闭 </a-button>
            </div>
        </template>
          <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>
<script>
import {
    addSettlementPlanning,
    getSettlementPlan,
    updateSettlementPlanning,
    deleteSettlementPlanning
} from '@/api/businessAffairs/revenueAndCost'

import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import Vue from 'vue'
export default {
    name: 'a' + Date.now(),
    props: {
        // 是否作为审批详情
        isAudit: {
            type: Boolean,
            default: false
        },
        // 是否作为意见征询
        isConsultation: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            checkVisibleInDetail: checkVisibleInDetail(this),
            form: { name: '', compleDate: '', createName: '' },
            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目' }],
                name: [{ required: true, message: '请输入名称' }],
                contractValue: [{ required: true, message: '请输入合同额（元）' }],
                confirmsProjectQuantity: [{ required: true, message: '请输入发包人确认工程量（元）' }],
                basicSettlementValue: [{ required: true, message: '请输入结算基本值（元）' }],
                settlementGuarantee: [{ required: true, message: '请输入结算保底值（元）' }],
                settlementReportValue: [{ required: true, message: '请输入结算报送值（元）' }],
                actualCost: [{ required: true, message: '请输入实际成本（元）' }],
                paidFor: [{ required: true, message: '请输入已收款（元）' }],
                reportingTime: [{ required: true, message: '请选择合同约定结算书报送时间' }],
                compleDate: [{ required: true, message: '请选择策划完成时间' }]
            },
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            id: '',
            isUpdate: true,
            type: '',
            token: '',
            title: '',
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    async created() {
        this.token = Vue.getAcloudProvider().getAccessToken()
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            this.getSettlementPlan()
        }
        this.type = this.$route.query.type
        //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('comm_construction_general_settle_plot_new')
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.type = 'look'
                    })
                }
            }
        }
    },
    methods: {
        getTime(date, dateString, type, name) {
            this[type][name] = dateString
            console.log(this[type][name])
        },
        fileArrysData: function (val) {
            this.form.fileInfoVOList = val
            console.log(val)
        },

        getSettlementPlan() {
            let params = {
                id: this.id
            }
            this.isUpdate = false
            getSettlementPlan(params).then((res) => {
                this.isUpdate = true
                this.form = { ...res.data }
                this.form.createName = this.$userInfo().name
                if(!this.form.name) {
                    this.form.name = this.form.projectName + '总包结算策划'
                }
            })
        },
        // 删除草稿
        deleteDraft() {
            let that = this
            that.$confirm({
                title: '温馨提示',
                content: '确定是否删除数据？',
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    return deleteSettlementPlanning({id:that.form.id,type:1})
                        .then((res) => {
                            that.$message.success('删除成功！')
                            that.closeForm()
                        })
                        .catch((res) => {
                            that.$message.warning('删除失败！')
                        })
                }
            })
        },
        // // 删除草稿
        // deleteDraft() {
        //     this.loading.DELETE = true
        //     deleteSettlementPlanning(this.form).then((res) => {
        //         this.loading.DELETE = false
        //         console.log(res)
        //         if (res.data.code == '200') {
        //             this.$message.success('删除成功')
        //             this.$multiTab.close(this.$route.fullpath)
        //             //  history.go(-1)
        //         }
        //     })
        // },

        // 提交表单
        submitForm(auditStatus) {
            this.setProcessConfig = null;
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (isAttachment(this, auditStatus, this.form.fileInfoVOList)) return
                    this.form.fileIdList = this.form.fileInfoVOList

                    this.loading[auditStatus] = true
                    this.form.auditStatus = auditStatus
                    this.submitApprovalConfirm(auditStatus =='SUBMITTED'?this.processConfig:6, (flag)=>{
                      if(!flag) {
                        this.loading[auditStatus] = false
                        return
                      }
                    if (this.id == '') {
                        addSettlementPlanning(this.form).then((res) => {
                            this.loading[auditStatus] = false
                            if (res.code == '200') {
                                this.$message.success(auditStatus === 'SUBMITTED' ? '提交成功' : '保存草稿成功')
                                if(auditStatus =='SUBMITTED') {
                                //提交时，返回id
                                this.businessId = res.data.id;
                                this.setProcessConfig = this.processConfig;
                                return
                                }else{
                                this.closeForm()
                                }
                            }
                        })
                    } else {
                        updateSettlementPlanning(this.form).then((res) => {
                            this.loading[auditStatus] = false
                            if (res.code == '200') {
                                this.$message.success(auditStatus === 'SUBMITTED' ? '提交成功' : '保存草稿成功')
                                if(auditStatus =='SUBMITTED') {
                                //提交时，返回id
                                    this.businessId = res.data.id;
                                    this.setProcessConfig = this.processConfig;
                                    return
                                }else{
                                this.closeForm()
                                }
                            }
                        })
                    }
                    })
                } else {
                  this.$message.warning("请填写完所有必填项信息")
                    console.log('error submit!!')
                    return false
                }
            })

            //
        },
        // 关闭表单
        closeForm() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
.step-text {
    .ant-steps-item-title {
        width: 168px;
    }
}
.check-box {
    .ant-checkbox-group {
        margin-top: 1.5%;
        display: flex;
        justify-content: space-between;
    }
    .ant-checkbox-group-item {
        position: static !important;
    }
}

.radio-box {
    .ant-radio-wrapper {
        position: static !important;
    }
    .ant-radio-group {
        margin-top: 3% !important;
        display: flex;
    }
}

.foot-btn {
    display: flex;
    justify-content: flex-end;
}
.prompt-bg {
    padding-top: 24px;
    background-color: #e4e1e1;
}
</style>
